package cn.tedu.tmall.basic.startup;

import cn.tedu.tmall.basic.service.IDistrictService;
import cn.tedu.tmall.basic.service.ILockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Component
public class SystemStartup implements InitializingBean,ApplicationRunner {

    /**
     * 1 通过static
     * 2
     */
    @Autowired()
    @Qualifier("DistrictServiceInitAllImpl")
    //@Qualifier("DistrictServiceInitByParentImpl")
    private IDistrictService districtService;
    @Autowired
    private  ILockService ilockService;

    public static void init() {

        System.out.println("通过 static init开始初始化数据库数据到redis....");
        //我们处理业务的时候抛了异常,导致我们tomcat启动失败
        //这样合理么? 合理的
        //throw new RuntimeException();
    }

    @PostConstruct
    public void Construct(){
        //districtService.initDict();
        System.out.println("通过 @PostConstruct 开始初始化数据库数据到redis...." + districtService);
        //throw new RuntimeException();
    }

    @PreDestroy
    public void  Destroy(){
        System.out.println("Destroy 被执行");
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        //实现从数据库查询省市区数据到redis
        //1 mapper 查询数据
        //2 redisTemplate 去set 数据
        long start = System.currentTimeMillis();
        log.debug("开始进行省市区缓存预热,开始时间:{}",start);


        log.debug("省市区缓存预热-开始获取分布式锁");
        Boolean lock = ilockService.lock();
        if (lock)
            log.debug("省市区缓存预热-分布式锁获取成功");
            try {
                districtService.initDict();
            }catch (Exception e){
                log.error("省市区缓存预热失败",e);
            }finally {
                ilockService.unlock();
                log.debug("省市区缓存预热-分布式锁释放成功");
            }

        long end = System.currentTimeMillis();
        log.debug("完成省市区缓存预热,开始时间:{},结束时间:{},耗时:{}",start,end,end-start);
        System.out.println("通过 ApplicationRunner.run 开始初始化数据库数据到redis...." + districtService);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("通过 afterPropertiesSet 开始初始化数据库数据到redis...." + districtService);
        //throw new RuntimeException();
    }
}
